from django.shortcuts import render

# Create your views here.
from django.views import View

from contents.models import ContentCategory
from goods.models import GoodsChannelGroup


class IndexView(View):
    def get(self, request):
        # 返回首页
        """
        {
            "1":{
                "channels":[   #  一个频道, 对应一个 一级分类
                    {"id":1, "name":"手机", "url":"http://shouji.jd.com/"},
                    {"id":2, "name":"相机", "url":"http://www.itcast.cn/"}
                ],
                "sub_cats":[
                    {
                        "id":38,
                        "name":"手机通讯",
                        "sub_cats":[
                            {"id":115, "name":"手机"},
                            {"id":116, "name":"游戏手机"}
                        ]
                    },
                    {
                        "id":39,
                        "name":"手机配件",
                        "sub_cats":[
                            {"id":119, "name":"手机壳"},
                            {"id":120, "name":"贴膜"}
                        ]
                    }
                ]
            },
            "2":{
                "channels":[],
                "sub_cats":[]
            }
        }
        """
        # 定义一个空字典, 来存放分类数据
        data = {}
        # 获取了所有的频道组
        channels_group_all = GoodsChannelGroup.objects.all()

        for channel_group in channels_group_all:
            channel_group_data = {
                "channels": [],
                "sub_cats": []
            }

            data[channel_group.id] = channel_group_data

            for channel in channel_group.goodschannel_set.all():
                cat1 = channel.category  # 找到渠道对应的一级分类
                channel_data = {"id": channel.id, "name": cat1.name, "url": channel.url}
                channel_group_data['channels'].append(channel_data)

                for cat2 in cat1.subs.all():
                    cat2_data = {
                        "id": cat2.id,
                        "name": cat2.name,
                        "sub_cats": []
                    }
                    channel_group_data['sub_cats'].append(cat2_data)

                    for cat3 in cat2.subs.all():
                        cat3_data = {"id": cat3.id, "name": cat3.name}
                        cat2_data['sub_cats'].append(cat3_data)

        # contents = {
        #     'index_lbt':[{
        #         'url':'',
        #         'image':'',
        #         'title':'',
        #
        #     },{},{}]
        # }
        # 获取首页内容
        contents = {}

        # 6, 拿到所有的分类

        categorys = ContentCategory.objects.all()
        # 7, 再把每个分类下面的内容取到
        for cat in categorys:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

        context = {
            "categories": data,
            "contents": contents
        }

        return render(request, 'index.html', context=context)
